package com.turing.post.common.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.LeftMenu;
import com.turing.post.common.util.SysOpAcl;
import com.turing.post.common.util.SysOpAclDao;
import com.turing.post.common.util.SysOpRole;
import com.turing.post.common.util.SysOpSap;
import com.turing.post.common.util.SysOpSapDao;
import com.turing.post.common.util.SysOpUserRole;
import com.turing.post.common.util.SysOpUserRoleDao;
import com.turing.post.util.Config;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;

/**
 * @author 张小盼
 * 
 */
@Stateless(mappedName = "common.impl.SysOpSapDaoImpl")
@Remote
@Local
public class SysOpSapDaoImpl implements SysOpSapDao {

	// 角色权限
	@EJB(mappedName = "common.impl.SysOpAclDaoImpl")
	private SysOpAclDao sysOpAclDaoImpl;

	@EJB(mappedName = "	common.impl.SysOpUserRoleDaoImpl")
	private SysOpUserRoleDao sysOpUserRoleDaoImpl;

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@SuppressWarnings("unchecked")
	public List<SysOpSap> getSysOpSapList(String sapName, Integer page) {
		String cond = "";
		if (!PCPSUtil.isEmpty(sapName)) {
			cond += " and sapName like '%" + sapName + "%'";
		}
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		Query query = _em.createNativeQuery(
				"select * from SysOpSap t where 1=1" + cond
						+ " order by SapId desc", SysOpSap.class)
				.setFirstResult(startPosition).setMaxResults(maxResult);
		return query.getResultList();
	}

	@Override
	public void deleteSysOpSap(Integer sapId) throws PCPSApplicationException {
		SysOpSap eo = getSysOpSapBySapId(sapId);
		if (eo != null) {
			GeneralDao.remove(_em, eo);
		}
	}

	@Override
	public BigInteger getMaxSapId() {
		Query query = _em
				.createNativeQuery("select nvl(max(SapId),0)+1 SapId from SysOpSap t");
		return ((BigDecimal) query.getSingleResult()).toBigInteger();
	}

	@Override
	public BigInteger getSysOpSapTotal(String sapName) {
		String cond = "";
		if (!PCPSUtil.isEmpty(sapName)) {
			cond += " and sapName like '%" + sapName + "%'";
		}
		Query query = _em
				.createNativeQuery("select nvl(count(*),0) from SysOpSap t where 1=1"
						+ cond);
		return new BigInteger(query.getSingleResult().toString());
	}

	@Override
	public SysOpSap getSysOpSapBySapId(Integer sapId) {
		return _em.find(SysOpSap.class, sapId);
	}

	@Override
	public void insertSysOpSap(SysOpSap sysOpSap)
			throws PCPSApplicationException {
		BigInteger sapId = getMaxSapId();
		sysOpSap.setSapId(sapId);
		// 自动为超级管理员添加权限
		SysOpAcl soa = new SysOpAcl();
		soa.setRoleId(SysOpRole.SUPER_ROLEID);
		soa.setSapId(sapId);
		sysOpSap.setIsAgency(SysOpSap.isNoagency);
		sysOpSap.setAgency(null);
		GeneralDao.insert(_em, sysOpSap);
		// 同步给超级管理员添加权限
		sysOpAclDaoImpl.insertSysOpAcl(soa);
	}

	@Override
	public void updateSysOpSap(SysOpSap sysOpSap)
			throws PCPSApplicationException {
		SysOpSap _sysOpSap = getSysOpSapBySapId(sysOpSap.getSapId().intValue());
		// 对象赋值
		_sysOpSap.setMenuId(sysOpSap.getMenuId());
		_sysOpSap.setSapName(sysOpSap.getSapName());
		_sysOpSap.setSapUrl(sysOpSap.getSapUrl());
		GeneralDao.update(_em, _sysOpSap);
	}

	// 角色分权限时根据菜单组选择
	@SuppressWarnings("unchecked")
	@Override
	public List<SysOpSap> getSysOpAclListByMenuGrpId(Integer menuGrpId) {
		String sql = "select a.sapid,a.sapname,a.menuid,a.sapseqno,a.sapurl from (select s.*,t.supermenuid,t.menuseqno from sysopsap s,sysopmenu t "
				+ "where s.menuid=t.menuid) a,(select t.menuid,t.menuseqno from sysopmenu t where t.supermenuid=?1) b "
				+ "where a.supermenuid=b.menuid order by a.menuseqno";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, menuGrpId);
		List<Object[]> result = query.getResultList();
		List<SysOpSap> resultList = new ArrayList<SysOpSap>();
		SysOpSap sos = null;
		for (int i = 0; i < result.size(); i++) {
			Object[] record = result.get(i);
			sos = new SysOpSap();
			sos.setSapId(((BigDecimal) record[0]).toBigInteger());
			sos.setSapName((String) record[1]);
			resultList.add(sos);
		}
		return resultList;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysOpSap> getSysOpAclListByRoleIdAndMenuGrpId(Integer roleId,
			Integer menuGrpId) {
		String sql = "select a.sapid,a.sapname,a.menuid,a.sapseqno,a.sapurl from "
				+ "(select s.*,t.supermenuid,t.menuseqno from sysopsap s,sysopmenu t,sysopacl c where s.menuid=t.menuid and s.sapid=c.sapid and "
				+ "c.roleid=?1) a,(select t.menuid,t.menuseqno from sysopmenu t where t.supermenuid=?2) b "
				+ "where a.supermenuid=b.menuid order by a.menuseqno";
		Query query = _em.createNativeQuery(sql);
		query.setParameter(1, roleId);
		query.setParameter(2, menuGrpId);
		List<Object[]> result = query.getResultList();
		List<SysOpSap> resultList = new ArrayList<SysOpSap>();
		SysOpSap sos = null;
		for (int i = 0; i < result.size(); i++) {
			Object[] record = result.get(i);
			sos = new SysOpSap();
			sos.setSapId(((BigDecimal) record[0]).toBigInteger());
			sos.setSapName((String) record[1]);
			resultList.add(sos);
		}
		return resultList;
	}

	@Override
	public void insertSysOpAclByRoleIdAndSapIdList(Integer menuGrpId,
			BigInteger roleId, List<BigInteger> sapIdList)
			throws PCPSApplicationException {
		SysOpAcl soa = null;
		sysOpAclDaoImpl.deleteSysOpAclByMenuGrpId(menuGrpId, roleId);
		if (sapIdList != null && sapIdList.size() > 0) {
			for (int i = 0; i < sapIdList.size(); i++) {
				soa = new SysOpAcl();
				soa.setRoleId(roleId);
				soa.setSapId(sapIdList.get(i));
				sysOpAclDaoImpl.insertSysOpAcl(soa);
			}
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public LeftMenu getTitleNameByMenuId(Integer menuId) {
		String sql = "select sg.menugrpname menuType,tx.menuname menuName,tx.name sapurl from sysopmenugroup sg,"
				+ "(select sm.menuname,sm.supermenuid,b.menuname name from sysopmenu sm,"
				+ "(select a.menuname,a.supermenuid from sysopsap t,sysopmenu a where t.menuid=a.menuid and a.menuid=?1) b "
				+ "where sm.menuid=b.supermenuid) tx where sg.menugrpid=tx.supermenuid";
		Query query = _em.createNativeQuery(sql, LeftMenu.class).setParameter(
				1, menuId);
		LeftMenu lm = null;
		List<LeftMenu> result = query.getResultList();
		if (result != null) {
			lm = result.get(0);
		}
		return lm;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysOpSap> getAgencySysOpSapList(String roleIds) {
		// SysOpUser user = sysOpUserDaoImpl.getSysOpUserByOperId(operId);
		String sql = "select * from sysopsap s where s.isagency='"
				+ SysOpSap.isagency
				+ "' and sapid in(select sapid from sysopacl t where t.roleid in("
				+ roleIds + ")) order by s.menuid asc";
		Query query = _em.createNativeQuery(sql, SysOpSap.class);
		List<SysOpSap> sapList = query.getResultList();
		List<SysOpSap> result = new ArrayList<SysOpSap>();
		SysOpSap _sap = null;
		SysOpSap sap = null;
		String url = null;
		for (int i = 0; i < sapList.size(); i++) {
			sap = sapList.get(i);
			_sap = new SysOpSap();
			_sap.setSapName(sap.getSapName());
			url = sap.getSapUrl();
			if (url.substring(url.length() - 3, url.length()).equals("jsp")) {
				url = url + "?id=" + sap.getMenuId();
			} else {
				url = url + "&id=" + sap.getMenuId();
			}
			_sap.setSapSeqNo(BigInteger.ZERO);
			_sap.setSapUrl(url);
			_sap.setAgency(sap.getAgency());
			result.add(_sap);
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<SysOpSap> getSysOpSapListByOperId(BigInteger operId) {
		List<SysOpUserRole> roleList = sysOpUserRoleDaoImpl
				.getSysOpUserRoleByOperId(operId);
		if (roleList == null || roleList.size() < 1) {
			return null;
		}
		String roleIds = getRoleIds(roleList);
		String sql = "select * from sysopsap s where "
				+ " sapid in(select sapid from sysopacl t where t.roleid in("
				+ roleIds + "))" + " order by s.menuid asc";
		Query query = _em.createNativeQuery(sql, SysOpSap.class);
		List<SysOpSap> sapList = query.getResultList();
		List<SysOpSap> result = new ArrayList<SysOpSap>();
		SysOpSap _sap = null;
		SysOpSap sap = null;
		String url = null;
		for (int i = 0; i < sapList.size(); i++) {
			sap = sapList.get(i);
			_sap = new SysOpSap();
			_sap.setSapName(sap.getSapName());
			url = sap.getSapUrl();
			if (url.substring(url.length() - 3, url.length()).equals("jsp")) {
				url = url + "?id=" + sap.getMenuId();
			} else {
				url = url + "&id=" + sap.getMenuId();
			}
			_sap.setSapSeqNo(BigInteger.ZERO);
			_sap.setSapUrl(url);
			_sap.setAgency(sap.getAgency());
			result.add(_sap);
		}
		return result;
	}

	private String getRoleIds(List<SysOpUserRole> roleList) {
		String result = "";
		for (int i = 0; i < roleList.size(); i++) {
			result += roleList.get(i).getRoleId() + ",";
		}
		return result.substring(0, result.length() - 1);
	}
}
